import React, { FC,useState,useEffect } from 'react'
import type {ChangeEvent} from 'react'
import { useNavigate,useLocation,useSearchParams } from 'react-router-dom'
import {Input} from 'antd'
import {LIST_SEARCH_PARAM_KEY} from '../constant/index.ts'
const { Search } = Input

const ListSearch: FC = ()=>{
    const nav = useNavigate()
    const { pathname } = useLocation()
    const [value,setValue] = useState('')
    // 获取url参数同步到搜索输入框
    const [searchParams] = useSearchParams()

    useEffect(()=>{
        const curVal = searchParams.get(LIST_SEARCH_PARAM_KEY) || ''
        setValue(curVal)
    },[searchParams])

    // 搜索
    const handleSearch = (value: string)=>{
        console.log('value',value);
        // 改变url
        nav({
            pathname,
            search:`${LIST_SEARCH_PARAM_KEY}=${value}`
        })
        
    }
    const handleChange = (event: ChangeEvent<HTMLInputElement>)=>{
        setValue(event.target.value)
    }

    return <Search placeholder="输入关键字" allowClear size="large" value={value} onChange={handleChange} onSearch={handleSearch} style={{ width: '200px' }} />
}

export default ListSearch